﻿using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace NoteHelper
{
    static class Program
    {
        private static log4net.ILog _logger;

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Occurs when an untrapped thread exception is thrown.
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            // Occurs when an exception is not caught.
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            // log4net 配置文件中，maxSizeRollBackups就是配置自动删除的
            //DeleteLogFileOver30Days();
            var configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CfgFiles\\log4net.cfg.xml");
            log4net.Config.XmlConfigurator.Configure(new FileInfo(configFile));
            _logger = log4net.LogManager.GetLogger("NoteHelper.Program");
            _logger.Info("logger init.");
            SettingForm settingForm = new SettingForm();
            if (!settingForm.DbFileExists())
            {
                settingForm.ShowDialog();
                settingForm.Dispose();
            }

            //Application.Run(new NavigateForm());
            Application.Run(new MainForm());
        }

        private static string LogDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");

        //private static void DeleteLogFileOver30Days()
        //{
        //    int day = 30;
        //    if (Directory.Exists(LogDir))
        //    {
        //        var files = Utils.IOHelper.GetAllFileList(LogDir)
        //                .Where(info => info.Extension.ToLower() == ".txt" && info.Name != "log.txt")
        //                .ToList();
        //        foreach (FileInfo info in files)
        //        {
        //            if (info.CreationTime.AddDays(day) < DateTime.Today)
        //                info.Delete();
        //        }
        //    }
        //}

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;
            NewMethod(ex);
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            NewMethod(e.Exception);
        }

        private static void NewMethod(Exception ex)
        {
            if (ex != null)
            {
                _logger.Error(ex);
            }
            string msg = ex.Message + " " + (ex.InnerException != null && ex.InnerException.Message != null && ex.Message != ex.InnerException.Message ? ex.InnerException.Message : "");
            MessageBox.Show("系统出现异常：" + msg);
        }
    }
}
